/**
 * 通用js(layui-admin)方法封装处理
 * by kimiloo
 */
var table;
var tableuse;
var tableIns;
(function ($) {
    $.extend({
    	bttTable: {},
		tablelist: {
			_option: {},
            // 初始化表格参数
            init: function(options) {
            	var defaults = {
					even: true
					,page: true
//					,type: 0 // 0 代表bootstrapTable 1代表bootstrapTreeTable
					,loading: true
					,autoSort: false
					,text: {none:'暂无数据'}//自定义文本，替换无数据
					,limit: 30
					,limits: [10,30,50,100,150,300,500]
					,parseData: function(res){ //res 即为原始返回的数据
						return {
							"code": res.code, //解析接口状态
							"msg": res.msg, //解析提示文本
							"count": res.count, //解析数据长度
							"data": res.data //解析数据列表
						};
					 }
//					,toolbar: '#toolbar'
					,defaultToolbar:[]
				};
				var options = $.extend(defaults, options);
                $.tablelist._option = options;
				tableuse =layui.use('table', function(){
					  table = layui.table;
					  tableIns = table.render(options);
				});
			},
			selectColumns: function(column) {
            	var rows = $.map($.btTable.bootstrapTable('getSelections'), function (row) {
        	        return row[column];
        	    });
            	if ($.common.isNotEmpty($.table._option.rememberSelected) && $.table._option.rememberSelected) {
            		rows = rows.concat(selectionIds);
            	}
            	return $.common.uniqueFn(rows);
            },
			//获取选中的行
            getCheckData: function(tableId){
            	var checkStatus = table.checkStatus(tableId)
                ,data = checkStatus.data;	
            	return data;
			},
			//获取所有行 返回数组对象
			allRows: function(){
				return tableuse.table.cache[options.id];
			},
			//通过数组对象，重新刷新列表  会清空table的url避免刷新table导致修改的数据还原为url数据
			load: function(data){
				var tmpurl = options.url;
				options.url = null;
				options.data = data;
				table.render(options);	
			},
			 //重载
			reload: function(){
				tableIns.reload(options);
			},
			//排序
			sort: function(dhtable,obj){
				if(!obj.type)obj.field = '';
				table.reload(dhtable, { //dhtableTable是表格容器id
					initSort: obj,
					where: {
						field: obj.field //排序字段
						,order: obj.type //排序方式
					}
				});
			},
			//获取载入参数
			getOptions: function(){
				return options;
			},
			//获取table上下文
			getTableContent: function(){
				return tableIns;
			},
			//选中某些行 filed判断字段 resourse需要选中行的数组对象
			selected: function(filed,resourse){
				if(filed&&resourse&&resourse.length>0){
					var allData = tablelist.allRows();
					$.each(allData, function(){
						var datadefine = this;
						var _value = eval('(datadefine.'+filed+')');
						for(var _m = 0;_m<resourse.length;_m++){
							if(_value==resourse[_m]){
								datadefine.LAY_CHECKED=true;
							}
						}
					});
					tablelist.load(allData);	
				}
			},
			//通过索引获取数据
			getByIndex: function(index){
				if(index!=undefined&&index!='undefined'){
					var allData = tablelist.allRows();
					
					for(var _m = 0;_m<allData.length;_m++){
						if(index==allData[_m].LAY_TABLE_INDEX){
							return allData[_m];
						}
					}
				}
			},
			//通过索引选中一行
			selectedByIndex: function(index){
				if(index!=undefined&&index!='undefined'){
					var allData = tablelist.allRows();
					$.each(allData, function(p1, p2){
						if(this.LAY_TABLE_INDEX==index){
							this.LAY_CHECKED=true;
						}
					});
					tablelist.load(allData);
				}
			},
			//通过索引取消选中一行
			unselectedByIndex: function(index){
				if(index!=undefined&&index!='undefined'){
					var allData = tablelist.allRows();
					$.each(allData, function(p1, p2){
						if(this.LAY_TABLE_INDEX==index){
							this.LAY_CHECKED=false;
						}
					});
					tablelist.load(allData);
				}
			},
			//选中所有
			selectedAll: function(){
				var allData = tablelist.allRows();
				$.each(allData, function(p1, p2){
					this.LAY_CHECKED=true;
				});
				tablelist.load(allData);
			},
			//取消选中所有
			unselectedAll: function(){
				var allData = tablelist.allRows();
				$.each(allData, function(p1, p2){
					this.LAY_CHECKED=false;
				});
				tablelist.load(allData);
			},
			//更新索引所在的行
			updateRow: function(index,data){
				if(index!=undefined&&index!='undefined'&&data){
					var allData = tablelist.allRows();
					var loadData=[];
					$.each(allData, function(){
						if(this.LAY_TABLE_INDEX==index){
							loadData.push(data);
						}else{
							loadData.push(this);
						}
					});
					tablelist.load(loadData);
				}
			},
			//在最后面插入一行
			appendAfterRow: function(data){
				if(data){
					var allData = tablelist.allRows();
					allData.push(data);
					tablelist.load(allData);
				}
			},
			//在最前面插入一行
			appendBeforeRow: function(data){
				if(data){
					var allData = tablelist.allRows();
					var loadData=[];
					loadData.push(data);
					$.each(allData, function(){
						loadData.push(this);
					});
					tablelist.load(loadData);
				}
			},
			//在索引后插入一行
			insertRow: function(index,data){
				if(index!=undefined&&index!='undefined'&&data){
					var allData = tablelist.allRows();
					var loadData=[];
					$.each(allData, function(){
						loadData.push(this);
						if(this.LAY_TABLE_INDEX==index){
							loadData.push(data);
						}
					});
					tablelist.load(loadData);
				}
			},
			//通过索引删除一行
			deleteRow: function(index){
				if(index!=undefined&&index!='undefined'){
					var allData = tablelist.allRows();
					var loadData=[];
					$.each(allData, function(){
						if(this.LAY_TABLE_INDEX!=index){
							loadData.push(this);
						}
					});
					tablelist.load(loadData);
				}
			},
			// 回显数据字典
            selectDictLabel: function(datas, value) {
            	var actions = [];
                $.each(datas, function(index, dict) {
                    if (dict.dictValue == ('' + value)) {
                    	var listClass = $.common.equals("default", dict.listClass) || $.common.isEmpty(dict.listClass) ? "" : "badge badge-" + dict.listClass;
                    	actions.push($.common.sprintf("<span class='%s'>%s</span>", listClass, dict.dictLabel));
                        return false;
                    }
                });
                return actions.join('');
            },
            // 导入数据
            importExcel: function(tableId, importFields, listData, moduleTable, decimalObj) {
            	layer.open({
            		type: 1,
            		area: ['400px', '230px'],
            		fix: false,
            		offset: '10%',
            		//不固定
            		maxmin: true,
            		shade: 0.3,
            		title: '导入数据',
            		content: $('#importTpl').html(),
            		btn: ['<i class="dhicon dh-check"></i> 导入', '<i class="dhicon dh-remove"></i> 取消'],
            		// 弹层外区域关闭
            		shadeClose: true,
            		btn1: function(index, layero){
            			var file = layero.find('#file');
            			if(!file[0]['value']){
            				layer.msg("请选择文件！");
            				return false;
            			}
            			var imRes = importExcel(file[0], tableId, importFields, listData, moduleTable, decimalObj);
            			if(imRes)layer.close(index);
            		}
            	});
            },
            // 下载模板
    		importTemplate: function(importTemplateUrl) {
    			$.get(importTemplateUrl, function(result) {
    				if (result.code == web_status.SUCCESS) {
    			        window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
				        parent.$('.page-loading').hide();//页面进行了跳转刷新，需要手动关闭页面的加载动画
    				} else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg)
                    } else {
    					$.modal.alertError(result.msg);
    				}
    			});
            },
            //导出
            exportExcel: function () {
            	$.ajax({
            		url: $.tablelist._option.exportUrl,
            		type: 'GET',
            		data: wherestr,
            		dataType: 'json',
            		beforeSend: function () {
            			showloadings(true);
            		},
            		success: function (result) {
            			if (result.code == 0) {
            				window.location.href = ctx + "common/download?fileName=" + encodeURIComponent(result.msg) + "&delete=" + true;
            				parent.$('.page-loading').hide(); //页面进行了跳转刷新，需要手动关闭页面的加载动画
            			} else if (result.code == web_status.WARNING) {
            				$.modal.alertWarning(result.msg)
            			} else {
            				$.modal.alertError(result.msg);
            			}
            			showloadings(false);
            		}
            	});
            }
		},
		// 表格树封装处理
        treeTable: {
            // 初始化表格
            init: function(options) {
            	var defaults = {
            		id: "bootstrap-tree-table",
                    type: 1, // 0 代表bootstrapTable 1代表bootstrapTreeTable
        		    height: 0,
        		    rootIdValue: null,
        		    ajaxParams: {},
        		    toolbar: "toolbar",
        		    striped: false,
        		    expandColumn: 1,
        		    showSearch: true,
        		    showRefresh: true,
        			showColumns: true,
        			expandAll: true,
        			expandFirst: true
        		};
            	var options = $.extend(defaults, options);
                $.tablelist._option = options;
                $.bttTable = $('#' + options.id).bootstrapTreeTable({
                	code: options.code,                                 // 用于设置父子关系（自己的主键）
        		    parentCode: options.parentCode,                     // 用于设置父子关系（父亲的主键）
        	    	type: 'post',                                       // 请求方式（*）
        	        url: options.url,                                   // 请求后台的URL（*）
        	        data: options.data,                                 // 无url时用于渲染的数据
        	        ajaxParams: options.ajaxParams,                     // 请求数据的ajax的data属性
        	        rootIdValue: options.rootIdValue,                   // 设置指定根节点id值
        	        height: options.height,                             // 表格树的高度
        			expandColumn: options.expandColumn,                 // 在哪一列上面显示展开按钮
        			striped: options.striped,                           // 是否显示行间隔色
        			bordered: true,                                     // 是否显示边框
        			toolbar: '#' + options.toolbar,                     // 指定工作栏
        			showSearch: options.showSearch,                     // 是否显示检索信息
        			showRefresh: options.showRefresh,                   // 是否显示刷新按钮
        			showColumns: options.showColumns,                   // 是否显示隐藏某列下拉框
        			expandAll: options.expandAll,                       // 是否全部展开
        			expandFirst: options.expandFirst,                   // 是否默认第一级展开--expandAll为false时生效
        	        columns: options.columns,                           // 显示列信息（*）
        	        responseHandler: $.treeTable.responseHandler        // 当所有数据被加载时触发处理函数
        	    });
            },
            // 条件查询
            search: function(formId) {
            	var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
            	var params = $.common.formToJSON(currentId);
            	$.bttTable.bootstrapTreeTable('refresh', params);
            },
            // 刷新
            refresh: function() {
            	$.bttTable.bootstrapTreeTable('refresh');
            },
            // 查询表格树指定列值
            selectColumns: function(column) {
            	var rows = $.map($.bttTable.bootstrapTreeTable('getSelections'), function (row) {
        	        return row[column];
        	    });
            	return $.common.uniqueFn(rows);
            },
            // 请求获取数据后处理回调函数，校验异常状态提醒
            responseHandler: function(data) {
            	if (data.code != undefined && data.code != 0) {
            		$.modal.alertWarning(data.msg);
            		return [];
                } else {
                    return data.data; //神坑，layui返回的data获取为data.data
                }
            },
        },
        // 表单封装处理
    	form: {
    		// 表单重置
    		/*reset: function(formId, tableId) {
            	var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
            	$("#" + currentId)[0].reset();
            	if ($.table._option.type == table_type.bootstrapTable) {
            	    if($.common.isEmpty(tableId)){
            	    	//$.btTable.bootstrapTable('refresh');
                	} else{
                	    //$("#" + tableId).bootstrapTable('refresh');
                	}
            	}
            },*/
            // 获取选中复选框项
            selectCheckeds: function(name) {
            	var checkeds = "";
        	    $('input:checkbox[name="' + name + '"]:checked').each(function(i) {
        	        if (0 == i) {
        	        	checkeds = $(this).val();
        	        } else {
        	        	checkeds += ("," + $(this).val());
        	        }
        	    });
        	    return checkeds;
            },
            // 获取选中下拉框项
            selectSelects: function(name) {
            	var selects = "";
        	    $('#' + name + ' option:selected').each(function (i) {
        	        if (0 == i) {
        	        	selects = $(this).val();
        	        } else {
        	        	selects += ("," + $(this).val());
        	        }
        	    });
        	    return selects;
            }
        },
        // 弹出层封装处理
    	modal: {
    		// 显示图标
    		icon: function(type) {
            	var icon = "";
        	    if (type == modal_status.WARNING || type == web_status.WARNING) {
        	        icon = 0;
        	    } else if (type == modal_status.SUCCESS || type == web_status.SUCCESS) {
        	        icon = 1;
        	    } else if (type == modal_status.FAIL || type == web_status.FAIL) {
        	        icon = 2;
        	    } else {
        	        icon = 3;
        	    }
        	    return icon;
            },
    		// 消息提示
            msg: function(content, type) {
            	if (type != undefined) {
                    layer.msg(content, { icon: $.modal.icon(type), offset: '10%', shift: 5 });
                } else {
                    layer.msg(content);
                }
            },
            // 错误消息
            msgError: function(content) {
            	$.modal.msg(content, modal_status.FAIL);
            },
            // 成功消息
            msgSuccess: function(content) {
            	$.modal.msg(content, modal_status.SUCCESS);
            },
            // 警告消息
            msgWarning: function(content) {
            	$.modal.msg(content, modal_status.WARNING);
            },
    		// 弹出提示
            alert: function(content, type) {
        	    layer.alert(content, {
        	        icon: $.modal.icon(type),
        	        offset: '10%',
        	        title: "系统提示",
        	        btn: ['确认'],
        	        btnclass: ['btn btn-primary'],
        	    });
            },
            // 消息提示并刷新父窗体
            msgReload: function(msg, type) {
            	layer.msg(msg, {
            	    icon: $.modal.icon(type),
            	    time: 500,
            	    shade: [0.1, '#8F8F8F']
            	},
            	function() {
            	    $.modal.reload();
            	});
            },
            // 错误提示
            alertError: function(content) {
            	$.modal.alert(content, modal_status.FAIL);
            },
            // 成功提示
            alertSuccess: function(content) {
            	$.modal.alert(content, modal_status.SUCCESS);
            },
            // 警告提示
            alertWarning: function(content) {
            	$.modal.alert(content, modal_status.WARNING);
            },
            // 关闭窗体
            close: function () {
            	var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            },
            // 关闭全部窗体
            closeAll: function () {
                layer.closeAll();
            },
            // 确认窗体
            confirmCom: function (content, callBack) {
            	layer.confirm(content, {
        	        icon: 3,
        	        offset: '10%',
        	        title: "系统提示",
					shadeClose:true,
        	        btn: ['确认', '取消'],
        	        yes: function(index){
        	        	callBack(true);
        			},
        			btn2: function(){
        				//layer.closeAll();
        				return true;
        			}
        	    }
            	/*, function (index) {
        	    	layer.close(index);
        	        callBack(true);
        	    }*/
            	);
            },
            /*
             * post_serialize
             * */
            openHtml: function (title, width, height, did, purl, calssdata, callback, infoItems, post_serialize){
            	var infoItems = infoItems || "infoItems";
            	layer.open({
        			type: 1,
        			area: [width + 'px', height + 'px'],
        			offset: '10%',
        			title: title,
        			shade: 0.6,
        			shadeClose: true,
        			maxmin: true,
        			content: $('#'+did),
        			btn: ['保存', '取消'],
        			yes: function(index){
        				if(post_serialize){
        					var form_data = $("."+calssdata).serialize();
        				}else{
        					var infoArr = {}, form_data = {};
        					$.each($("."+calssdata).serializeArray(), function(i, field){
        						infoArr[field.name] = field.value;
        				    });
        					form_data[infoItems] = JSON.stringify([infoArr]);
        				}
        				$.operate.post(purl,form_data,callback);
        				$("."+calssdata)[0].reset();
        				layui.form.render();
        				layer.closeAll();
        			},
        			btn2: function(){
        				$("."+calssdata)[0].reset();
        				layui.form.render();
        				layer.closeAll();
        			},
        			end: function(){$("."+calssdata)[0].reset();layui.form.render();}
        		}); 
            },
            // 弹出层指定宽度
            open: function (title, url, width, height, callback, offset,btn=['确定', '关闭']) {
            	//如果是移动端，就使用自适应大小弹窗
            	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            	    width = 'auto';
            	    height = 'auto';
            	}
            	if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = "/404.html";
                }
                if ($.common.isEmpty(width)) {
                	width = ($(window).width() - 300);
                }
                if ($.common.isEmpty(height)) {
                	height = ($(window).height() - 150);
                }
                if(width>$(window).width())width=($(window).width() - 100);//如果宽 度超过屏幕宽度
            	if(height>$(window).height())height=($(window).height() - 50);//如果高度超过屏幕高度
                if ($.common.isEmpty(offset)) {
                	offset = '6%';
                }
                if ($.common.isEmpty(callback)) {
                    callback = function(index, layero) {
                    	var submit = layero.find('iframe').contents().find("#btn_save");
                    	if(submit.length==1){
            				var iframeWindow = window['layui-layer-iframe'+ index];
    						iframeWindow.layui.form.on('submit(btn_save)', function(data){//监听当前窗口的表单提交事件
    							var iframeWin = layero.find('iframe')[0];
    	            	        iframeWin.contentWindow.submitHandler(index, layero);//执行窗口的submitHandler方法
    						});
    						submit.click();//模拟单击保存按钮
            			}else{
                            var iframeWin = layero.find('iframe')[0];
                            iframeWin.contentWindow.submitHandler(index, layero);//执行窗口的submitHandler方法
            			}
                    }
                }
            	layer.open({
            		type: 2,
            		area: [width + 'px', height + 'px'],
            		offset: offset,//距离顶部10%
            		fix: false,
            		//不固定
            		maxmin: true,
            		shade: 0.6,
            		title: title,
            		content: url,
            		btn: btn,
            	    //点击弹层外区域关闭
            		shadeClose: true,
            		yes: callback,
            	    cancel: function(index) {
            	        return true;
            	    }
            	});
            },
            // 弹出层打开页面代码
            openInnerHtml: function (title, iHtml, width, height, callback) {
            	//如果是移动端，就使用自适应大小弹窗
            	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            	    width = 'auto';
            	    height = 'auto';
            	}
            	if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(iHtml)) {
                	layer.msg('请提供html代码!');
                    return false;
                }
                if ($.common.isEmpty(width)) {
                	width = 800;
                }
                if ($.common.isEmpty(height)) {
                	height = ($(window).height() - 150);
                }
                if ($.common.isEmpty(callback)) {
                    callback = function(index, layero) {
                    	if(layero.find('iframe').contents().find("#btn_save").length==1){
            				var iframeWindow = window['layui-layer-iframe'+ index],submit = layero.find('iframe').contents().find("#btn_save");
    						//保存按钮单击事件
    						iframeWindow.layui.form.on('submit(btn_save)', function(data){
    							var iframeWin = layero.find('iframe')[0];
    	            	        iframeWin.contentWindow.submitHandler(index, layero); //执行窗口的submitHandler方法
    						});  
    						submit.click();
            			}else{
                            var iframeWin = layero.find('iframe')[0];
                            iframeWin.contentWindow.submitHandler(index, layero);
            			}
                    }
                }
            	layer.open({
            		type: 1,
            		area: [width + 'px', height + 'px'],
            		offset: '6%',//距离顶部10%
            		fix: false,
            		//不固定
            		maxmin: true,
            		shade: 0.6,
            		title: title,
            		content: iHtml,
            		btn: ['确定', '关闭'],
            	    //点击弹层外区域关闭
            		shadeClose: true,
            		yes: callback,
            	    cancel: function(index) {
            	        return true;
            	    }
            	});
            },
            // 弹出层指定参数选项
            openOptions: function (options) {
            	var _url = $.common.isEmpty(options.url) ? "/404.html" : options.url; 
            	var _title = $.common.isEmpty(options.title) ? "系统窗口" : options.title; 
                var _width = $.common.isEmpty(options.width) ? "800" : options.width; 
                var _height = $.common.isEmpty(options.height) ? ($(window).height() - 50) : options.height;
                var _btn = ['<i class="dhicon dh-check"></i> 确认', '<i class="dhicon dh-close"></i> 关闭'];
                if ($.common.isEmpty(options.yes)) {
                	options.yes = function(index, layero) {
                    	options.callBack(index, layero);
                    }
                }
                layer.open({
                    type: 2,
            		maxmin: true,
                    shade: 0.3,
                    title: _title,
                    fix: false,
                    area: [_width + 'px', _height + 'px'],
                    content: _url,
                    shadeClose: $.common.isEmpty(options.shadeClose) ? true : options.shadeClose,
                    skin: options.skin,
                    btn: $.common.isEmpty(options.btn) ? _btn : options.btn,
                    yes: options.yes,
                    cancel: function () {
                        return true;
                    }
                });
            },
            // 弹出层全屏
            openFull: function (title, url, callback, width, height) {
            	//如果是移动端，就使用自适应大小弹窗
            	if (navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)) {
            	    width = 'auto';
            	    height = 'auto';
            	}
            	if ($.common.isEmpty(title)) {
                    title = false;
                }
                if ($.common.isEmpty(url)) {
                    url = "/404.html";
                }
                if ($.common.isEmpty(width)) {
                	width = 800;
                }
                if ($.common.isEmpty(height)) {
                	height = ($(window).height() - 50);
                }
                var index = layer.open({
            		type: 2,
            		area: [width + 'px', height + 'px'],
            		fix: false,//不固定
            		maxmin: false,//最大小化
            		shade: 0.3,
            		title: title,
            		content: url,
            		btn: ['确定', '关闭'],
            		shadeClose: true,
            		yes: callback?callback:function(index, layero) {
            			var iframeWindow = window['layui-layer-iframe'+ index],submit = layero.find('iframe').contents().find("#btn_save");
						//保存按钮单击事件
						iframeWindow.layui.form.on('submit(btn_save)', function(data){
							var iframeWin = layero.find('iframe')[0];
	            	        iframeWin.contentWindow.submitHandler(index, layero); //执行窗口的submitHandler方法
						});  
						submit.click();
            	    },
            	    cancel: function(index) {
            	        return true;
            	    }
            	});
                layer.full(index);
            },
            // 简单弹出层（无按钮）
            openSimple: function (title, url, width, height, callback) {
            	layer.open({
            		type: 2,
            		area: [width + 'px', height + 'px'],
            		offset: '10%',//距离顶部10%
            		fix: false,
            		maxmin: true,
            		shade: 0.6,
            		title: title,
            		content: url,
            		shadeClose: false,
            		btn: ['关闭'],
            	    yes: callback?callback:function(index, layero) {
            	    	layer.close(index);
            	    },
            	});
            },
            // 选卡页方式打开
            openTab: function (title, url) {
            	createMenuItem(url, title);
            },
            // 选卡页同一页签打开
            parentTab: function (title, url) {
            	var dataId = window.frameElement.getAttribute('data-id');
            	createMenuItem(url, title);
            	closeItem(dataId);
            },
            // 关闭选项卡
            closeTab: function (dataId) {
            	closeItem(dataId);
            },
            // 禁用按钮
            disable: function() {
            	var doc = window.top == window.parent ? window.document : window.parent.document;
	        	$("a[class*=layui-layer-btn]", doc).addClass("layer-disabled");
            },
            // 启用按钮
            enable: function() {
            	var doc = window.top == window.parent ? window.document : window.parent.document;
            	$("a[class*=layui-layer-btn]", doc).removeClass("layer-disabled");
            },
            // 打开遮罩层
            loading: function (message) {
            	$.blockUI({ message: '<div class="loaderbox"><div class="loading-activity"></div> ' + message + '</div>' });
            },
            // 关闭遮罩层
            closeLoading: function () {
            	setTimeout(function(){
            		$.unblockUI();
            	}, 50);
            },
            // 重新加载
            reload: function () {
            	parent.location.reload();
            }
        },
        //文件上传
        uploadFile:{
        	common: function (objID, upUrl, type, ext='', dataObj={}, multiple=true, reloadUrl=''){
        		upload.render({
        			elem: objID
                    ,url: upUrl
                    ,multiple: multiple
                    ,accept: type //普通文件
                    ,exts: ext
        			,data: dataObj
        			,before: function(obj){
        				layer.load(2, {shade: [0.1, '#000']});
    			    }
                    ,done: function(res){
                    	if(res.code == '0'){
                    		dataObj['fileSize'] = res.data.fileSize;
                    		dataObj['fileType'] = res.data.fileType;
                    		dataObj['fileName'] = res.data.fileName;
                    		dataObj['fileSizeUnit'] = res.data.fileSizeUnit;
                    		dataObj['filePath'] = res.data.filePath;
                    		// 添加文件记录
							$.ajax({
								type: "POST",
								url: '/system/fileinfo/addFilesInfo',
								data: dataObj,
								success: function (data) {
									if (data.code == 0) {
		                        		setTimeout(function(){
		                        			if(reloadUrl){
		            				            table.reload('dhtable', {url: reloadUrl,page:{curr: 1}});
		                        			}else{
		                        				window.location.reload();
		                        			}
		        		                }, 1000);
									} else {
										alert(data.msg);
									}
								}
							});
                    	}
                    	if(!multiple){
                    		console.log(res);
                        	if(res.code == '0'){
                        	}else{
                        		$.modal.alert(res.msg,'warning');
                        	}
                        	layer.closeAll('loading');
                    	}
                    }
                    ,allDone: function(obj){ //当文件全部被提交后，才触发
                        layer.msg("成功上传"+obj.successful+"个文件");
                        layer.closeAll('loading');
                        setTimeout(function(){
                        	if(reloadUrl){
    				            table.reload('dhtable', {url: reloadUrl,page:{curr: 1}});
    				            $.uploadFile.common(objID, upUrl, type, '', dataObj, true, reloadUrl);
                			}else{
                				window.location.reload();
                			}
		                }, 1000);
                    }
        		})
        	}
        },
        // 操作封装处理
        operate: {
        	// 提交数据
        	submit: function(url, type, dataType, data, callback,async=true,traditional=false) {
            	var config = {
        	        url: url,
        	        type: type,
        	        dataType: dataType,
					data: data,
					async:async,
					traditional:traditional,
        	        beforeSend: function () {
        	        	$.modal.loading("正在处理中，请稍后...");
        	        },
        	        success: function(result) {
        	        	if (typeof callback == "function") {
        	        	    callback(result);
        	        	}
        	        	$.operate.ajaxSuccess(result);
        	        }
        	    };
        	    $.ajax(config)
            },
            // post请求传输
            post: function(url, data, callback,async,traditional) {
            	$.operate.submit(url, "post", "json", data, callback,async,traditional);
            },
            // get请求传输
            get: function(url, callback) {
            	$.operate.submit(url, "get", "json", "", callback);
            },
            // 详细信息
            detail: function(id, width, height) {
            	var _url = $.operate.detailUrl(id);
            	var options = {
       				title: $.tablelist._option.modalName + "详细",
       				width: width,
       				height: height,
       				url: $.operate.detailUrl(id),
       				skin: 'layui-layer-gray', 
       				btn: ['关闭'],
       				yes: function (index, layero) {
       	                layer.close(index);
                    }
       			};
            	$.modal.openOptions(options);
            },
            // 详细访问地址
            detailUrl: function(id) {
            	var url = "/404.html";
            	if ($.common.isNotEmpty(id)) {
            	    url = $.tablelist._option.detailUrl.replace("{id}", id);
            	} else {
            	    var id = $.common.isEmpty($.table._option.uniqueId) ? $.tablelist.selectFirstColumns() : $.tablelist.selectColumns($.table._option.uniqueId);
            	    if (id.length == 0) {
            			$.modal.alertWarning("请至少选择一条记录");
            			return;
            		}
            	    url = $.table._option.detailUrl.replace("{id}", id);
            	}
                return url;
            },
            // 删除信息
            remove: function(content, url, data, callback) {
            	$.modal.confirmCom(content, function() {
	            	    $.operate.post(url, data, callback);
            	});
            	
            },
            // 批量删除信息
            removeAll: function() {
        		var rows = $.common.isEmpty($.table._option.uniqueId) ? $.table.selectFirstColumns() : $.table.selectColumns($.table._option.uniqueId);
        		if (rows.length == 0) {
        			$.modal.alertWarning("请至少选择一条信息");
        			return;
        		}
        		$.modal.confirm("确认要删除选中的" + rows.length + "条数据吗?", function() {
        			var url = $.table._option.removeUrl;
        			var data = { "ids": rows.join() };
        			$.operate.submit(url, "post", "json", data);
        		});
            },
            // 清空信息
            clean: function() {
            	$.modal.confirmCom("确定清空所有" + $.tablelist._option.modalName + "吗？", function() {
	            	var url = $.tablelist._option.cleanUrl;
	            	$.operate.submit(url, "post", "json", "");
	            	setTimeout(function(){
	                    layer.closeAll();
	                    table.reload('dhtable');
	                }, 1000);
            	});
            },
            // 添加信息
            add: function(id,width,height) {
                $.modal.open("添加" + $.tablelist._option.modalName, $.operate.addUrl(id),width,height);
            },
            // 添加信息，以tab页展现
            addTab: function (id) {
                $.modal.openTab("添加" + $.table._option.modalName, $.operate.addUrl(id));
            },
            // 添加信息 全屏
            addFull: function(id) {
                $.modal.openFull("添加" + $.tablelist._option.modalName, $.operate.addUrl(id));
            },
            // 添加访问地址
            addUrl: function(id) {
            	var url = $.common.isEmpty(id) ? $.tablelist._option.createUrl.replace("{id}", "") : $.tablelist._option.createUrl.replace("{id}", id);
            	return url;
            },
            // 修改信息
            edit: function(id,width,height) {
            	if($.common.isEmpty(id)) {
            		var row = $.bttTable.bootstrapTreeTable('getSelections')[0];
                	if ($.common.isEmpty(row)) {
            			$.modal.alertWarning("请至少选择一条记录");
            			return;
            		}
                    var url = $.tablelist._option.updateUrl.replace("{id}", row[$.tablelist._option.uniqueId],width,height);
                    $.modal.open("修改" + $.tablelist._option.modalName, url);
            	} else {
            		$.modal.open("修改" + $.tablelist._option.modalName, $.operate.editUrl(id),width,height);
            	}
            },
            // 修改信息，以tab页展现
            editTab: function(id) {
            	$.modal.openTab("修改" + $.table._option.modalName, $.operate.editUrl(id));
            },
            // 修改信息 全屏
            editFull: function(id) {
            	var url = "/404.html";
            	if ($.common.isNotEmpty(id)) {
            	    url = $.tablelist._option.updateUrl.replace("{id}", id);
            	} else {
            	    var row = $.common.isEmpty($.table._option.uniqueId) ? $.tablelist.selectFirstColumns() : $.tablelist.selectColumns($.table._option.uniqueId);
            	    url = $.tablelist._option.updateUrl.replace("{id}", row);
            	}
            	$.modal.openFull("修改" + $.tablelist._option.modalName, url);
            },
            // 修改访问地址
            editUrl: function(id) {
            	var url = "/404.html";
            	if ($.common.isNotEmpty(id)) {
            	    url = $.tablelist._option.updateUrl.replace("{id}", id);
            	} else {
            	    var id = $.common.isEmpty($.tablelist._option.uniqueId) ? $.tablelist.selectFirstColumns() : $.tablelist.selectColumns($.tablelist._option.uniqueId);
            	    if (id.length == 0) {
            			$.modal.alertWarning("请至少选择一条记录");
            			return;
            		}
            	    url = $.tablelist._option.updateUrl.replace("{id}", id);
            	}
                return url;
            },
            // 保存信息 刷新表格
            save: function(url, data, callback) {
            	var config = {
        	        url: url,
        	        type: "post",
        	        dataType: "json",
        	        data: data,
        	        beforeSend: function () {
        	        	$.modal.loading("正在处理中，请稍后...");
        	        	$.modal.disable();
        	        },
        	        success: function(result) {
        	        	if (typeof callback == "function") {
        	        	    callback(result);//方法带回调函数则启用
        	        	    $.modal.closeLoading();
        	        	}else{
							$.operate.successCallback(result);//默认成功回调执行事件（父窗体静默更新）
						}
        	        }
        	    };
        	    $.ajax(config)
            },
            // 保存信息 弹出提示框
            saveModal: function(url, data, callback) {
            	var config = {
        	        url: url,
        	        type: "post",
        	        dataType: "json",
        	        data: data,
        	        beforeSend: function () {
        	        	$.modal.loading("正在处理中，请稍后...");
        	        },
        	        success: function(result) {
        	        	if (typeof callback == "function") {
        	        	    callback(result);
        	        	}
        	        	if (result.code == web_status.SUCCESS) {
	                        $.modal.alertSuccess(result.msg)
	                    } else if (result.code == web_status.WARNING) {
	                        $.modal.alertWarning(result.msg)
	                    } else {
	                    	$.modal.alertError(result.msg);
	                    }
        	        	$.modal.closeLoading();
        	        }
        	    };
        	    $.ajax(config)
            },
            // 保存选项卡信息
            saveTab: function(url, data, callback) {
            	var config = {
        	        url: url,
        	        type: "post",
        	        dataType: "json",
        	        data: data,
        	        beforeSend: function () {
        	        	$.modal.loading("正在处理中，请稍后...");
        	        },
        	        success: function(result) {
        	        	if (typeof callback == "function") {
        	        	    callback(result);
        	        	}
        	        	$.operate.successTabCallback(result);
        	        }
        	    };
        	    $.ajax(config)
            },
            // 保存结果弹出msg刷新table表格
            ajaxSuccess: function (result) {
            	if (result.code == web_status.SUCCESS) {
                	$.modal.msgSuccess(result.msg);
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                	$.modal.alertError(result.msg);
                }
            	$.modal.closeLoading();
            },
            // 成功结果提示msg（父窗体全局更新）
            saveSuccess: function (result) {
            	if (result.code == web_status.SUCCESS) {
            		$.modal.msgReload("保存成功,正在刷新数据请稍后……", modal_status.SUCCESS);
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                }  else {
                	$.modal.alertError(result.msg);
                }
            	$.modal.closeLoading();
            },
            // 成功回调执行事件（父窗体静默更新）
            successCallback: function(result) {
                if (result.code == web_status.SUCCESS) {
                	var parent = window.parent;
                    if (parent.$.tablelist._option.type == table_type.bootstrapTable){
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.table.refresh();
                    } else if (parent.$.tablelist._option.type == table_type.bootstrapTreeTable) {
                        $.modal.close();
                        parent.$.modal.msgSuccess(result.msg);
                        parent.$.treeTable.refresh();
                    } else {
                        $.modal.msgReload("保存成功,正在刷新数据请稍后……", modal_status.SUCCESS);
                    }
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                }  else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
                $.modal.enable();
            },
            // 选项卡成功回调执行事件（父窗体静默更新）
            successTabCallback: function(result) {
                if (result.code == web_status.SUCCESS) {
                	var topWindow = $(window.parent.document);
    	            var currentId = $('.page-tabs-content', topWindow).find('.active').attr('data-panel');
    	            var $contentWindow = $('.RuoYi_iframe[data-id="' + currentId + '"]', topWindow)[0].contentWindow;
    	            $.modal.close();
    	            $contentWindow.$.modal.msgSuccess(result.msg);
    	            $contentWindow.$(".layui-layer-padding").removeAttr("style");
    	            if ($contentWindow.$.table._option.type == table_type.bootstrapTable) {
    	        		$contentWindow.$.table.refresh();
    	        	} else if ($contentWindow.$.table._option.type == table_type.bootstrapTreeTable) {
    	        		$contentWindow.$.treeTable.refresh();
                    }
    	            $.modal.closeTab();
                } else if (result.code == web_status.WARNING) {
                    $.modal.alertWarning(result.msg)
                } else {
                    $.modal.alertError(result.msg);
                }
                $.modal.closeLoading();
            }
        },
        // 校验封装处理
        validate: {
        	// 判断返回标识是否唯一 false 不存在 true 存在
        	unique: function (value) {
            	if (value == "0") {
                    return true;
                }
                return false;
            },
            // 表单验证
            form: function (formId) {
            	var currentId = $.common.isEmpty(formId) ? $('form').attr('id') : formId;
            	return $("#" + currentId).validate().form();
            }
        },
        // 树插件封装处理
        tree: {
        	_option: {},
        	_lastValue: {},
        	// 初始化树结构
        	init: function(options) {
        		var defaults = {
            		id: "tree",                    // 属性ID
            		expandLevel: 0,                // 展开等级节点
            		view: {
    			        selectedMulti: false,      // 设置是否允许同时选中多个节点
    			        nameIsHTML: true           // 设置 name 属性是否支持 HTML 脚本
    			    },
            		check: {
    				    enable: false,             // 置 zTree 的节点上是否显示 checkbox / radio
    				    nocheckInherit: true,      // 设置子节点是否自动继承
    				},
    				data: {
    			        key: {
    			            title: "title"         // 节点数据保存节点提示信息的属性名称
    			        },
    			        simpleData: {
    			            enable: true           // true / false 分别表示 使用 / 不使用 简单数据模式
    			        }
    			    },
        		};
            	var options = $.extend(defaults, options);
        		$.tree._option = options;
        		// 树结构初始化加载
        		var setting = {
    				callback: {
    			        onClick: options.onClick,                      // 用于捕获节点被点击的事件回调函数
    			        onCheck: options.onCheck,                      // 用于捕获 checkbox / radio 被勾选 或 取消勾选的事件回调函数
    			        onDblClick: options.onDblClick                 // 用于捕获鼠标双击之后的事件回调函数
    			    },
    				check: options.check,
    			    view: options.view,
    			    data: options.data
    			};
        	    $.get(options.url, function(data) {
        			var treeId = $("#treeId").val();
        			tree = $.fn.zTree.init($("#" + options.id), setting, data);
        			$._tree = tree;
        			var nodes = tree.getNodesByParam("level", options.expandLevel - 1);
        			for (var i = 0; i < nodes.length; i++) {
        				tree.expandNode(nodes[i], true, false, false);
        			}
        			var node = tree.getNodesByParam("id", treeId, null)[0];
        			$.tree.selectByIdName(treeId, node);
        		});
        	},
        	// 搜索节点
        	searchNode: function() {
        		// 取得输入的关键字的值
        		var value = $.common.trim($("#keyword").val());
        		if ($.tree._lastValue == value) {
        		    return;
        		}
        		// 保存最后一次搜索名称
        		$.tree._lastValue = value;
        		var nodes = $._tree.getNodes();
        		// 如果要查空字串，就退出不查了。
        		if (value == "") {
        		    $.tree.showAllNode(nodes);
        		    return;
        		}
        		$.tree.hideAllNode(nodes);
        		// 根据搜索值模糊匹配
        		$.tree.updateNodes($._tree.getNodesByParamFuzzy("name", value));
        	},
        	// 根据Id和Name选中指定节点
        	selectByIdName: function(treeId, node) {
        		if ($.common.isNotEmpty(treeId) && treeId == node.id) {
        			$._tree.selectNode(node, true);
        		}
        	},
        	// 显示所有节点
        	showAllNode: function(nodes) {
        		nodes = $._tree.transformToArray(nodes);
        		for (var i = nodes.length - 1; i >= 0; i--) {
        		    if (nodes[i].getParentNode() != null) {
        		    	$._tree.expandNode(nodes[i], true, false, false, false);
        		    } else {
        		    	$._tree.expandNode(nodes[i], true, true, false, false);
        		    }
        		    $._tree.showNode(nodes[i]);
        		    $.tree.showAllNode(nodes[i].children);
        		}
        	},
        	// 隐藏所有节点
        	hideAllNode: function(nodes) {
        	    var tree = $.fn.zTree.getZTreeObj("tree");
        	    var nodes = $._tree.transformToArray(nodes);
        	    for (var i = nodes.length - 1; i >= 0; i--) {
        	    	$._tree.hideNode(nodes[i]);
        	    }
        	},
        	// 显示所有父节点
        	showParent: function(treeNode) {
        		var parentNode;
        		while ((parentNode = treeNode.getParentNode()) != null) {
        			$._tree.showNode(parentNode);
        			$._tree.expandNode(parentNode, true, false, false);
        		    treeNode = parentNode;
        		}
        	},
        	// 显示所有孩子节点
        	showChildren: function(treeNode) {
        		if (treeNode.isParent) {
        		    for (var idx in treeNode.children) {
        		        var node = treeNode.children[idx];
        		        $._tree.showNode(node);
        		        $.tree.showChildren(node);
        		    }
        		}
        	},
        	// 更新节点状态
        	updateNodes: function(nodeList) {
        		$._tree.showNodes(nodeList);
        		for (var i = 0, l = nodeList.length; i < l; i++) {
        		    var treeNode = nodeList[i];
        		    $.tree.showChildren(treeNode);
        		    $.tree.showParent(treeNode)
        		}
        	},
        	// 获取当前被勾选集合
        	getCheckedNodes: function(column) {
        		var _column = $.common.isEmpty(column) ? "id" : column;
        		var nodes = $._tree.getCheckedNodes(true);
        		return $.map(nodes, function (row) {
        	        return row[_column];
        	    }).join();
        	},
        	// 不允许根父节点选择
        	notAllowParents: function(_tree) {
    		    var nodes = _tree.getSelectedNodes();
    		    if(nodes.length == 0){
                    $.modal.msgError("请选择节点后提交");
                    return false;
				}
    		    for (var i = 0; i < nodes.length; i++) {
    		        if (nodes[i].level == 0) {
    		            $.modal.msgError("不能选择根节点（" + nodes[i].name + "）");
    		            return false;
    		        }
    		        if (nodes[i].isParent) {
    		            $.modal.msgError("不能选择父节点（" + nodes[i].name + "）");
    		            return false;
    		        }
    		    }
        		return true;
        	},
        	// 不允许最后层级节点选择
        	notAllowLastLevel: function(_tree) {
    		    var nodes = _tree.getSelectedNodes();
    		    for (var i = 0; i < nodes.length; i++) {
                    if (!nodes[i].isParent) {
    		    		$.modal.msgError("不能选择最后层级节点（" + nodes[i].name + "）");
    		            return false;
    		        }
    		    }
        		return true;
        	},
        	// 隐藏/显示搜索栏
        	toggleSearch: function() {
        		$('#search').slideToggle(200);
        		$('#btnShow').toggle();
        		$('#btnHide').toggle();
        		$('#keyword').focus();
        	},
        	// 折叠
        	collapse: function() {
        		$._tree.expandAll(false);
        	},
        	// 展开
        	expand: function() {
        		$._tree.expandAll(true);
        	}
        },
        // 通用方法封装处理
    	common: {
    		// 判断字符串是否为数值（默认不可为负数）
            isNumber: function (value,canMinus=false) {
				if(canMinus)return new RegExp("^-?[0-9]+([.]{1}[0-9]+){0,1}$").test(value);
				else return new RegExp("^[0-9]+([.]{1}[0-9]+){0,1}$").test(value);
			},
    		// 判断字符串是否为空
            isEmpty: function (value) {
                if (value == null || this.trim(value) == "" || value == "undefined") {
                    return true;
                }
                return false;
            },
            // 判断一个字符串是否为非空串
            isNotEmpty: function (value) {
            	return !$.common.isEmpty(value);
            },
            // 空对象转字符串
            nullToStr: function(value) {
                if ($.common.isEmpty(value)) {
                    return "-";
                }
                return value;
            },
            // 是否显示数据 为空默认为显示
            visible: function (value) {
                if ($.common.isEmpty(value) || value == true) {
                    return true;
                }
                return false;
            },
            // 空格截取
            trim: function (value) {
                if (value == null) {
                    return "";
                }
                return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
            },
            // 比较两个字符串（大小写敏感）
            equals: function (str, that) {
            	return str == that;
            },
            // 比较两个字符串（大小写不敏感）
            equalsIgnoreCase: function (str, that) {
            	return String(str).toUpperCase() === String(that).toUpperCase();
            },
            // 将字符串按指定字符分割
            split: function (str, sep, maxLen) {
            	if ($.common.isEmpty(str)) {
            	    return null;
            	}
            	var value = String(str).split(sep);
            	return maxLen ? value.slice(0, maxLen - 1) : value;
            },
            // 字符串格式化(%s )
            sprintf: function (str) {
                var args = arguments, flag = true, i = 1;
                str = str.replace(/%s/g, function () {
                    var arg = args[i++];
                    if (typeof arg === 'undefined') {
                        flag = false;
                        return '';
                    }
                    return arg;
                });
                return flag ? str : '';
            },
            // 指定随机数返回
            random: function (min, max) {
                return Math.floor((Math.random() * max) + min);
            },
            // 判断字符串是否是以start开头
            startWith: function(value, start) {
                var reg = new RegExp("^" + start);
                return reg.test(value)
            },
            // 判断字符串是否是以end结尾
            endWith: function(value, end) {
                var reg = new RegExp(end + "$");
                return reg.test(value)
            },
            // 数组去重
            uniqueFn: function(array) {
                var result = [];
                var hashObj = {};
                for (var i = 0; i < array.length; i++) {
                    if (!hashObj[array[i]]) {
                        hashObj[array[i]] = true;
                        result.push(array[i]);
                    }
                }
                return result;
            },
            // 数组中的所有元素放入一个字符串
            join: function(array, separator) {
            	if ($.common.isEmpty(array)) {
            	    return null;
            	}
                return array.join(separator);
            },
            // 获取form下所有的字段并转换为json对象
            formToJSON: function(formId) {
            	 var json = {};
                 $.each($("#" + formId).serializeArray(), function(i, field) {
                	 json[field.name] = field.value;
                 });
            	return json;
            }
        }
    });
})(jQuery);

/** 表格类型 */
table_type = {
    bootstrapTable: 0,
    bootstrapTreeTable: 1
};

/** 消息状态码 */
web_status = {
	SUCCESS: 0,
	FAIL: 500,
	WARNING: 301
};

/** 弹窗状态码 */
modal_status = {
    SUCCESS: "success",
    FAIL: "error",
    WARNING: "warning",
    CONFIRM: 'info'
};